// Delete Empty fields
action = "deleteEmptyFields";
$.post("/ajax/actions",{action:action}, function(){
    
});
$(document).ready(function() {
//----------------------------------------------------------------------------------------//
/*-----Update Records Page-----*/
$(".btupdate_invoice").live("click", function(){
    action = $(this).attr("action");
    locFile = $(this).attr("rel");
    $("#load").show();
    $.post("/ajax/update/",{action:action,locFile:locFile}, function(res){
        if(res == 'Folder location is empty.'){
            showNotification({
                message: "Folder location is empty.",
                type: "error",
                autoClose: true,
                duration: 5
            });
            $("#load").hide();
        }
        else{
            if(res == 'Invalid File Format.'){
                showNotification({
                    message: "Invalid File Format.",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
                $("#load").hide();
            }
            else
            {
                
                if(res == 'File is already uploaded.'){
                    $("#load").hide();
                    showNotification({
                        message: "File is already uploaded.",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    /*
                    $("#warn").show().fadeOut(3000);
                    
                    $("#warning").hide();
                    $("#correct").hide();
                    */
                }else{
                    if(res == 'Files was successfully uploaded.'){
                        showNotification({
                            message: "Files was successfully uploaded.",
                            type: "success",
                            autoClose: true,
                            duration: 5
                        });
                        $("#load").hide();
                    }
                }
            }
        }
    });
});
$(".btupdate_product").live("click", function(){
    action = $(this).attr("action");
    locFile = $(this).attr("rel");
    $("#loadProduct").show();
    $.post("/ajax/uploadValidation/",{action:action,locFile:locFile}, function(res){
        if(res=="There was an Error while uploading your file."){
            showNotification({
                message: "There was an Error while uploading your file.",
                type: "error",
                autoClose: true,
                duration: 5
            });
            $("#loadProduct").hide();
        }else{
            if(res=="Folder location is empty."){
                showNotification({
                    message: "Folder location is empty.",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
                $("#loadProduct").hide();
            }else{
                if(res=="Invalid File Format."){
                    showNotification({
                        message: "Invalid File Format.",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    $("#loadProduct").hide();
                }else{
                    if(res=="File is already uploaded."){
                        showNotification({
                            message: "File is already uploaded.",
                            type: "error",
                            autoClose: true,
                            duration: 5
                        });
                        $("#loadProduct").hide();
                    }else{
                        if(res=="PLINE type doesnt match on our record."){
                            showNotification({
                                message: "PLINE type doesnt match on our record.",
                                type: "error",
                                autoClose: true,
                                duration: 5
                            });
                            $("#loadProduct").hide();
                        }else{
                            $.post("/ajax/update/",{action:action,locFile:locFile}, function(update){
                                showNotification({
                                    message: "File was successfully uploaded.",
                                    type: "success",
                                    autoClose: true,
                                    duration: 5
                                });
                                $("#loadProduct").hide();
                            });
                        }
                        
                    }
                }
            }
        }
        
    });
});

$(".btupdate_rewardPoints").live("click",function(){
    action = $(this).attr("action");
    locFile = $(this).attr("rel");
    $("#loadRewardPoints").show();
    $.post("/ajax/uploadValidation/",{action:action,locFile:locFile}, function(res){
        if(res=="There was an Error while uploading your file."){
            showNotification({
                message: "There was an Error while uploading your file.",
                type: "error",
                autoClose: true,
                duration: 5
            });
            $("#loadRewardPoints").hide();
        }else{
            if(res=="Folder location is empty."){
                showNotification({
                    message: "Folder location is empty.",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
                $("#loadRewardPoints").hide();
            }else{
                if(res=="Invalid File Format."){
                    showNotification({
                        message: "Invalid File Format.",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    $("#loadRewardPoints").hide();
                }else{
                    if(res=="File is already uploaded."){
                        showNotification({
                            message: "File is already uploaded.",
                            type: "warning",
                            autoClose: true,
                            duration: 5
                        });
                        $("#loadRewardPoints").hide();
                    }else{
                        $.post("/ajax/update/",{action:action,locFile:locFile}, function(update){
                            showNotification({
                                message: "File was successfully uploaded.",
                                type: "success",
                                autoClose: true,
                                duration: 5
                            });
                            $("#loadRewardPoints").hide();
                        });
                    }
                }
            }
        }
        
    });
});
//----------------------------------------------------------------------------------------//
/*-----Balance Inquiry Page-----*/

//First load for Dealer
    trans_id = "";
    dealer_id = "";
    action = "default";
    //search dealers record from the database
    page = 1;
    $.post("/ajax/balance_inquiry/", {action:action,page:page}, function(reports){
            //$("#generateReport").html(reports);
            $(".loadDealer").html(reports);
            $(".dealerPointsList").html(null);
    });
    //for pagination
    $('.pagination li.active').live('click',function(){
    var page = $(this).attr('p');
    valueSearch = $(this).attr("data-value");
    action = $(this).attr("data-tag-action");
    $.post("/ajax/balance_inquiry/", {action:action,value:valueSearch,page:page}, function(reports){
                //$("#generateReport").html(reports);
                $(".loadDealer").html(reports);
                $(".dealerPointsList").html(null);
        });
    });           
//For Searching Dealers
$("#searchDealer").keyup(function(){
    $(".dealerPointsList").html(null);
    value = $(this).val();
    action = "searchDealerName";
    //search dealers record from the database
    page = 1;
    $(".dealerRedeem").html(null);
    $.post("/ajax/balance_inquiry/", {action:action,value:value,page:page}, function(reports){
            //$("#generateReport").html(reports);
            $(".loadDealer").html(reports);
            //$(".dealerPointsList").html(null);
            $(".second_checkOut").hide();
    });
});
//Sort in Balance Inquiry
markBalAudit = 0;
$(".sortdealer").live("click",function(){
    sortBalRel = $(this).attr("rel");
    page = 1;
    action = "searchDealerName";
    value = $("#searchDealer").val();
    $.post("/ajax/balance_inquiry/", {value:value,sortBalRel:sortBalRel,action:action,page:page,markBalAudit:markBalAudit}, function(data){
            //$("#generateReport").html(reports);
            $(".loadDealer").html(data);
            //alert(data)
    });
    markBalAudit++;
})

//View Dealer Points
$("#viewDealerPoints").live("click",function(){
    secAction = $(this).attr("secAction");
    $(".dealerRedeem").html(null);
    $('html, body').animate({
                    scrollTop: $(".dealerPointsList").offset().top
                });
    ID = $(this).attr("rel");
    action = "viewDealerPoints";
    $("#load").show();
    $(".dealerPointsList").html(null);
    //Get Dealer Information Points from the database
    $.post("/ajax/point/", {action:action,ID:ID,secAction:secAction}, function(dealerPointsList){
        $(".dealerPointsList").html(dealerPointsList);
        $("#load").hide();
    });
    generateTrans_id = 1; //action for transaction ID
    $.post("/ajax/point/",{generateTrans_id:generateTrans_id,ID:ID},function(data){
        trans_id = data;
    })
    $(".cOC").html(null); 
    
    //for report
    $(".name").text("Dealer Name: "+$("#dealerName_"+ID).text()) //displaying the dealer name
    $(".print").css("display","inline-block"); // display the button print
    $(".allTrans").css("display","inline-block"); // display the button allTrans
    $(".allTrans").attr("dealerCode",ID) //assigning dealercode attribute "dealerCode"
    $(".forReport").css("display","inline-block"); //showing the classes
    $(".buts").attr("relDR",""); //clean the attribute relDR
    $(".buts").attr("relDPL",""); // clean the attribute relDPL
    $(".name").show(); //showing the dealer name
});
//Load More Result
$('.more').live("click",function() {
    ID = $(this).attr("id");
    dealerCode = $(this).attr("rel");
    lastRecord = $("#count_"+ID).attr("rel");
    totalShowRecord = lastRecord + parseInt(5);
    numColspan = $(this).attr("numColspan");
    if(ID){
        $(".morebox").html('<img src="/images/loader/moreajax.gif" />');
        $.ajax({
            type: "POST",
            url: "/ajax/loadmore/",
            data: "ID="+ ID + "&dealerCode=" + dealerCode + "&totalShowRecord=" + totalShowRecord + "&numColspan=" + numColspan, 
            cache: false,
            success: function(html){
                $("#loadMore").append(html);
                $("#more_"+ID).hide();
            }
        });
    }
    else{
        $("#more_"+ID).hide();
    }
    return false;
});
//----------------------------------------------------------------------------------------//
/*-----Reports Page-----*/
page = 1;
action = "searchDealerNameReport";
$.post("/ajax/reports/", {action:action,page:page}, function(reports){
        //$("#generateReport").html(reports);
        $(".loadDealerReport").html(reports);
});
//Summary Reports
$.post("/ajax/summary/", {action:"default",page:page}, function(reports){
        //$("#generateReport").html(reports);
        $(".loadSummary").html(reports);
});
$('.pagination li.active').live('click',function(){
var page = $(this).attr('p');
valueSearch = $(this).attr("data-value");
action = $(this).attr("data-tag-action");
    $.post("/ajax/reports/", {action:action,page:page,value:valueSearch}, function(reports){
            //$("#generateReport").html(reports);
            $(".loadDealerReport").html(reports);
            $(".dealerRedeem, .name, .buts").hide();
    });
    $.post("/ajax/summary/", {action:action,page:page,value:valueSearch}, function(reports){
            //$("#generateReport").html(reports);
            $(".loadSummary").html(reports);
    });
});     
// Search Users
$("#searchReports").keyup(function(){
    value = $(this).val();
    action = "searchDealerNameReport";
    $.post("/ajax/reports", { action:action,value:value,page:page } , function(e){
       $(".loadDealerReport").html(e);
    });
    $(".forReport").css("display","none");
});

//Sort in Report
markRepAudit = 0;
$(".sortRepdealer").live("click",function(){
    sortRepRel = $(this).attr("rel");
    page = 1;
    action = "searchDealerNameReport";
    value = $("#searchReports").val();
    $.post("/ajax/reports/", {value:value,sortRepRel:sortRepRel,action:action,page:page,markRepAudit:markRepAudit}, function(data){
            //$("#generateReport").html(reports);
            $(".loadDealerReport").html(data);
            //alert(data)
    });
    markRepAudit++;
})

$(".allTrans").live("click",function(){
    forSelect = "1";
    Points = $(this).attr("id");
    Name = $(this).attr("rel");
    userID = $(this).attr("dealerCode");
    $("#loadProducts").show();
    $(".dealerRedeem").html(null);
    $("#viewPoints").css("opacity","0.4");
    //open new window to show the product
    $.post("/ajax/view_product/", {Points:Points,Name:Name,userID:userID,forSelect:forSelect}, function(result){
    setTimeout(function(){
            $(".dealerRedeem").show().html(result);
            $("#loadProducts").hide();
            $('html, body').animate({
                    scrollTop: $(".dealerRedeem").offset().top
                });
            $("#viewPoints").css("opacity","1");
    }, 1000);
        
    });
})
// Summary Reports
/* Single Check of the checkbox for deleting the record from the database in data table */
    $(".singleSelectAll").live("click",function(){
	if(this.checked){
            // Select Single Checkbox
            var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
            return $(this).attr("rel"); // Get an ID of the document
            }).get().join(',');
            $("#documentListID").val(list); // Where the ID input in the textbox
        }else{
            // Remove Unchecked ID in the textbox
            var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
            return $(this).attr("rel");
            }).get().join(',');
            $("#documentListID").val(list);
        }
    });
/* Select All the checkbox in sinlge checked of the header Checkbox */
    $(".selectAll").live("click",function(){
        if(this.checked){
            $(".singleSelectAll").each(function(){
                $(this).attr("checked",true);
                var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                return $(this).attr("rel");
                }).get().join(',');
                $("#documentListID").val(list);
            });
        }else{
            $(".singleSelectAll").each(function(){
                $(this).attr("checked",false);
                var list = $(':checkbox[name="singleSelectAll[]"]:checked').map(function(){
                return $(this).attr("rel");
                }).get().join(',');
                $("#documentListID").val(list);
            });
        }
    });
    $(".printSelectedSummary").live("click",function(){
        redeem_id = $("#documentListID").val();
	action = $(this).attr("data-tag-action");
	if(redeem_id!=""){
            window.open('/ajax/gen_rep?id='+redeem_id+'','','width=750,height=500');
        }else{
            showNotification({
                message: "Please check atleast one checkbox in the table to proceed.",
                type: "error",
                autoClose: true,
                duration: 5
            });
        }
	
    })
$(".summaryRep").live("click", function(){
    startDValid = $("#startD").val();
    endDValid = $("#endD").val();
    page = 1;
    if(startDValid == "" || endDValid == ""){
        //alert("There's an empty field")
        showNotification({
            message: "There's an empty field",
            type: "error",
            autoClose: true,
            duration: 5
        });
    }else{
        startD = new Date($("#startD").val());
        endD = new Date($("#endD").val());
        valueSearch = startDValid+","+endDValid;
        userID = $(this).attr("rel");
        filter = "true";
        forSelect = 1;
        action = "Summary";
        if(startD<=endD){
            $.post("/ajax/summary/",{action:action,value:valueSearch,filter:filter,forSelect:forSelect,page:page},function(result){
                $(".loadSummary").html(result);
            })
        }else{
            alert(1)
        }
    }
});
//print
$(".print").click(function(){
    $(".dealerName").hide()
    $("#loadProducts").hide();
    $(".dateFilter").hide();
    $(".hide").hide();
    $(".morebox").hide();
    divToPrint = $(this).attr("rel");
    w=window.open();
    w.document.write($('.logo1').html()+"<hr />"+$(".name").html()+$('.'+divToPrint).html());
    w.document.close();
    w.focus();
    w.print();
    w.close();
    $(".dateFilter").show();
    $(".hide").show();
    $(".morebox").show();
    //$("#loadProducts").show();
})

//Filter Date
$(".filterD").live("click",function(){
    startDValid = $("#startD").val();
    endDValid = $("#endD").val();
    if(startDValid == "" || endDValid == ""){
        //alert("There's an empty field")
        showNotification({
            message: "There's an empty field",
            type: "error",
            autoClose: true,
            duration: 5
        });
    }else{
        startD = new Date($("#startD").val());
        endD = new Date($("#endD").val());
        userID = $(this).attr("rel");
        filter = "true";
        forSelect = 1;
        if(startD<=endD){
            $.post("/ajax/view_product/",{startD:startDValid,endD:endDValid,filter:filter,userID:userID,forSelect:forSelect},function(result){
                $(".dealerRedeem").html(result);
            })
        }else{
            alert(false)
        }
    }
})
//Hide Print Target
$("#hideDPL").live("click",function(){
    $(".buts").attr("relDPL","true"); //allocating the value to relDPL for condition to hide the headers
    relDR = $(".buts").attr("relDR");
    relDPL = $(".buts").attr("relDPL");
    if(relDR==relDPL){ //condition for hiding
        $(".buts").hide();
        $(".name").hide();
    }
    className = $(this).parent().parent().parent().attr("class");
    countStr = className.length;
    trueClassName = "";
    for(a=0;a<countStr;a++){
        if(className.substr(a,1)==" "){
            trueClassName = className.substr(0,a);
        }
    }
    $("."+trueClassName).slideUp();
})
$("#hideDR").live("click",function(){
    $(".buts").attr("relDR","true"); //allocating the value to relDR for condition to hide the headers
    relDR = $(".buts").attr("relDR"); // assign relDR to variable
    relDPL = $(".buts").attr("relDPL"); // assign relDPL to variable
    if(relDR==relDPL){ //condition for hiding
        $(".buts").hide();
        $(".name").hide();
    }
    className = $(this).parent().parent().parent().parent().attr("class");
    countStr = className.length;
    trueClassName = "";
    for(a=0;a<countStr;a++){
        if(className.substr(a,1)==" "){
            trueClassName = className.substr(0,a);
        }
    }
    $("."+trueClassName).slideUp();
})
//----------------------------------------------------------------------------------------//

/*-----Audit Trail Page-----*/
//default view
page = 1;
action = "auditSearch";
$.post("/ajax/audit-trail", {action:action,page:page}, function(data){
        //$("#generateReport").html(reports);
        $("#loadAudit").html(data);
});
$('.'+action+' li.active').live('click',function(){
var page = $(this).attr('p');
valueSearch = $(this).attr("data-value");
action = $(this).attr("data-tag-action");
$.post("/ajax/audit-trail", {action:action,value:valueSearch,page:page}, function(data){
            //$("#generateReport").html(reports);
            $("#loadAudit").html(data);
    });
});     
// search audit trail record from the database
$("#searchAudit").keyup(function(){
    value = $(this).val();
    action = "auditSearch";
    $.post("/ajax/audit-trail", { action:action,value:value,page:page } , function(data){
       $("#loadAudit").html(data);
    });
});


// ERROR Update list
action = "errorSearch";
$.post("/ajax/error_update", {action:action,page:page}, function(data){
        //$("#generateReport").html(reports);
        $("#loadError").html(data);
});
$('.'+action+' li.active').live('click',function(){
var page = $(this).attr('p');
valueSearch = $(this).attr("data-value");
action = $(this).attr("data-tag-action");
$.post("/ajax/error_update", {action:action,value:valueSearch,page:page}, function(data){
            //$("#generateReport").html(reports);
            $("#loadError").html(data);
    });
});     
// search audit trail record from the database
$("#searchError").keyup(function(){
    value = $(this).val();
    action = "errorSearch";
    $.post("/ajax/error_update", { action:action,value:value,page:page } , function(data){
       $("#loadError").html(data);
    });
});

//sort
markSortAudit = 0;
$(".sortAudit").live("click",function(){
    sortAuditRel = $(this).attr("rel");
    page = 1;
    action = "auditSearch";
    value = $("#searchAudit").val();
    $.post("/ajax/audit-trail/", {value:value,sortAuditRel:sortAuditRel,action:action,page:page,markSortAudit:markSortAudit}, function(data){
            //$("#generateReport").html(reports);
            $("#loadAudit").html(data);
    });
    markSortAudit++;
})
/*-----User Maintenance Page-----*/
//default
page = 1;
action = "userSearch";
$.post("/ajax/userMaintenance/", {action:action,page:page}, function(reports){
        //$("#generateReport").html(reports);
        $("#loadUser").html(reports);
});
$('.pagination li.active').live('click',function(){
var page = $(this).attr('p');

valueSearch = $(this).attr("data-value");
action = $(this).attr("data-tag-action");
$.post("/ajax/userMaintenance/", {action:action,value:valueSearch,page:page}, function(reports){
            //$("#generateReport").html(reports);
            $("#loadUser").html(reports);
    });
});     
// Search Users
$("#searchUser").keyup(function(){
    value = $(this).val();
    action = "userSearch";
    $("#repButtons").css("display","none");
    $(".printArea").css("display","none");
    $.post("/ajax/userMaintenance", { action:action,value:value,page:page } , function(e){
       $("#loadUser").html(e);
    });
});
//sort
markSortUser = 0;
$(".sortuser").live("click",function(){
    sortUserRel = $(this).attr("rel");
    page = 1;
    action = "userSearch";
    value = $("#searchUser").val();
    $.post("/ajax/userMaintenance", {value:value,sortUserRel:sortUserRel,action:action,page:page,markSortUser:markSortUser}, function(data){
            //$("#generateReport").html(reports);
            $("#loadUser").html(data);
    });
    markSortUser++;
})
// View add user form
$("#addNewUser").live("click",function(){
    $("#addUser").show().fadeIn(); // View user Forms
    //Set to go in the user form to create new user
    $('html, body').animate({
        scrollTop: $(".addUser").offset().top
    });
});
//Hide add user form
$("#hideForm").live("click",function(){
    //Set back to top when user click the hide button
    $('html, body').animate({
        scrollTop: $("body").offset().top
    });
    $("#addUser").hide().fadeOut(); // hide user Forms
    $("#newUsername").val(null);
    $("#newFirstname").val(null);
    $("#newPassword").val(null);
    $("#newLastname").val(null);
    
});
// Click to edit user
$(".editUser").live("click",function(){
    ID = $(this).attr("rel"); // ID of the user
    
    //Hide Label 
    $("#username_"+ID).hide();
    $("#firstname_"+ID).hide();
    $("#lastname_"+ID).hide();
    $("#loa_"+ID).hide();
    $("#password_"+ID).hide();
        //hide button
        $("#edit_"+ID).hide();
        $("#editDel_"+ID).hide();
    //Show Textfield
    $("#editUsername_"+ID).show();
    $("#editFirstname_"+ID).show();
    $("#editLastname_"+ID).show();
    $("#editLOA_"+ID).show();
    $("#editPassword_"+ID).show();
        //Show Save Button
        $("#save_"+ID).show();
});
// Click to save edited user
$(".saveUser").live("click",function(){
    ID = $(this).attr("rel");
    //Saving to Database
    username = $("#editUsername_"+ID).val();
    firstname = $("#editFirstname_"+ID).val();
    lastname = $("#editLastname_"+ID).val();
    userlevel = $("#editLOA_"+ID).val();
    password = $("#editPassword_"+ID).val();
    userlevel_text = $("#editLOA_"+ID+" option:selected").text();
    //alert(userlevel_text)
    //alert("id: "+ID+"\nusername: "+username+"\nfirstname: "+firstname+"\nlastname: "+lastname+"\nuserlevel: "+userlevel);
    $.post("/ajax/userMaintenance/",{action:"editUser",ID:ID,username:username,firstname:firstname,lastname:lastname,loa:userlevel,password:password},function(data){
        if(data=="There's an Empty Field."){
            //alert("There's an empty field.");
            showNotification({
                message: "There's an Empty Field.",
                type: "error",
                autoClose: true,
                duration: 5
            });
        }else{
            if(data=="Please Input Correct Format of your firstname and lastname."){
                //alert("");
                showNotification({
                    message: "Please Input Correct Format of your firstname and lastname.",
                    type: "warning",
                    autoClose: true,
                    duration: 5
                });
            }else{
                if(data=="Username is already Taken."){
                    
                    showNotification({
                        message: "Username is already Taken.",
                        type: "warning",
                        autoClose: true,
                        duration: 5
                    });
                }else{
                    /*
                    $("#username_"+ID).html(username);
                    $("#firstname_"+ID).html(firstname);
                    $("#lastname_"+ID).html(lastname);
                    $("#loa_"+ID).html(userlevel_text);
                    $("#password_"+ID).html(password);
                    //Show Label 
                    $("#username_"+ID).show();
                    $("#firstname_"+ID).show();
                    $("#lastname_"+ID).show();
                    $("#loa_"+ID).show();
                    $("#password_"+ID).show();
                        //hide button
                        $("#edit_"+ID).show();
                        $("#editDel_"+ID).show();
                    //Hide Textfield
                    $("#editUsername_"+ID).hide();
                    $("#editFirstname_"+ID).hide();
                    $("#editLastname_"+ID).hide();
                    $("#editLOA_"+ID).hide();
                    $("#editPassword_"+ID).hide();
                        //Show Save Button
                        $("#save_"+ID).hide();
                    */
                    //$("body").load("/user_maintenance/").fadeIn('fast');
                    window.location.reload();
                }
            }
            
        }
    })
});
// Click to delete user
$(".deleteUser").live("click",function(){
    action = "deleteUser";
    ID = $(this).attr("rel");
    dataString = "action=" + action + "&ID=" + ID;
    con = "Are you sure do you want to delete this user?";
    //delete user from the database
    if(confirm(con))
    {
        $.ajax({
            type: "POST",
            url: "/ajax/userMaintenance/",
            data: dataString,
            success: function(e){
                if(e=="User was successfully deleted."){
                    showNotification({
                        message: "User was successfully deleted.",
                        type: "success",
                        autoClose: true,
                        duration: 5
                    });
                }
            }
        });
        $(this).parents("#deleteRow_"+ID).animate({ backgroundColor: "#fbc7c7"}, "fast").animate({ opacity: "hide"}, "slow");
    }
});
// Add User to the database
$(".saveNewUser").live("click",function(){
    username = $("#newUsername").val();
    firstname = $("#newFirstname").val();
    lastname = $("#newLastname").val();
    loa = $("#newLOA").val();
    password = $("#newPassword").val();
    action = "addUser";
    dataString = 'action=' + action + '&username=' + username + '&firstname=' + firstname +
    '&lastname=' + lastname + '&loa=' + loa + '&password=' + password;
    //Save to the database.
    $.ajax({
        type: "POST",
        url: "/ajax/userMaintenance/",
        data: dataString,
        success: function(data)
        {
            //Notification if user is wrong or correct
                //alert(data)
            if(data=="Please fill those required fields."){
                $(".wrongNotification").show();
                $("#wrong").html(data);
                $(".wrongNotification").show().fadeOut(3000);
            }else{
                if(data=="Please input the correct format for your name."){
                    $(".wrongNotification").show();
                    $("#wrong").html(data);
                    $(".wrongNotification").show().fadeOut(3000);
                }else{
                    if(data=="Username is already taken."){
                        $(".wrongNotification").show();
                        $("#wrong").html(data);
                        $(".wrongNotification").show().fadeOut(3000);
                    }else{
                        if(data=="New user was successfully saved."){
                            $(".correctNotification").show();
                            $("#correct").html(data);
                            setTimeout(function(){  
                                //$("body").load("/user_maintenance/").fadeIn('fast');
                                window.location.reload("/user_maintenance/");
                            }, 2000);
                        }
                    }
                }
            }
        }
    });
});
/* Changing Username of the user */
$(".changeUsername").live("click", function(){
    newUsername = $("#newUsername").val(); // new username
    action = "newUsername";
    if(newUsername==""){
        //alert("Please input your new username.");
        $(".wrongNotification1").show().fadeOut(3000);
        $("#wrong1").html("Please input your new username.");
        
    }else{
        $.post("/ajax/actions/",{action:action,newUsername:newUsername}, function(e){
            $(".correctNotification1").show().fadeOut(3000);
            $("#correct1").html("You username was successfully changed.");
            //alert("You username was successfully changed.");
            $("#oldUsername").val(newUsername); // change the value of the old user to a new one
            $("#newUsername").val(null);
            setTimeout(function(){
                window.location.reload();
            }, 2000);
            
        });
    }
});
/* Changing password of the user */
$(".changePassword").live("click", function(){
    oldPassword = $("#oldPassword").val();
    newPassword = $("#newPassword").val();
    retypePassword = $("#retypePassword").val();
    action = "newPassword";
    if(oldPassword=="" || newPassword==""|| retypePassword==""){
        
        //alert("Please fill those required fields.");
        $(".wrongNotification").show().fadeOut(5000);
        $("#wrong").html("Please fill those required fields.");
    }else{
        if(newPassword!=retypePassword){
            
            //alert("Your new password and retype password is not the same.");
            $(".wrongNotification").show().fadeOut(5000);
            $("#wrong").html("Your new password and retype password is not the same.");
        }else{
            $.post("/ajax/actions/",{action:action,newPassword:newPassword,oldPassword:oldPassword}, function(e){
                if(e=="no"){
                    
                    //alert("Your Old password does'nt match in our records.");
                    $(".wrongNotification").show().fadeOut(5000);
                    $("#wrong").html("Your Old password does'nt match in our records.");
                }else{
                    //alert("You password was successfully changed.");
                    $(".correctNotification").show().fadeOut(3000);
                    $("#correct").html("You password was successfully changed.");
                    $("#oldPassword").val(null);
                    $("#newPassword").val(null);
                    $("#retypePassword").val(null);
                    setTimeout(function(){
                        window.location.reload();
                    }, 2000);
                }
                
            });
        }
    }
});
// Changing account details
$(".changeAccountDetails").live("click", function(){
    newFname = $("#newFirstname").val();
    newLname = $("#newLastname").val();
    action = "newAccountDetails";
    if(newFname==""||newLname==""){
        $(".wrongNotificationAcc").show().fadeOut(5000);
        $("#wrongAcc").html("Please input your firstname / lastname in the field.");
    }else{
       $.post("/ajax/actions/",{action:action,newFname:newFname,newLname:newLname}, function(e){
            if(e=="Successfull"){
                $(".correctNotificationAcc").show().fadeOut(5000);
                $("#correctAcc").html("Account detail's was successfully updated.");
                $("#userfullname").html("Welcome, <u><b>"+ newFname + " " + newLname+"</b></u>");
                $("#newFirstname").val(null);
                $("#newLastname").val(null);
            }
        
        });
    }
    
    
});
// Getting Product List by its Points
$(".get_products").live("click", function(){
    Points = $(this).attr("id");
    Name = $(this).attr("rel");
    userID = $(this).attr("dealerCode");
    header = $(this).attr("data-header");
    $("#loadProducts").show();
    $(".dealerRedeem").html(null);
    $("#viewPoints").css("opacity","0.4");
    //open new window to show the product
    $.post("/ajax/product/", {Points:Points,Name:Name,userID:userID,header:header}, function(result){
    setTimeout(function(){
            $(".dealerRedeem").css("display","inline-block")
            $(".dealerRedeem").html(result);
            $("#loadProducts").hide();
            $('html, body').animate({
                    scrollTop: $(".dealerRedeem").offset().top
                });
            $("#viewPoints").css("opacity","1");
    }, 1000);
    });
    oldProd = [];
});
$(".BactToTop").live("click", function(){
    $('html, body').animate({
                    scrollTop: $(".dealerPointsList").offset().top
                });
    $(".dealerRedeem").html(null);
    //con = confirm("Do you wish to proceed? It will cancel your current transactions.");
    //if(con){
        
    //}else{
        
    //}
    
});
//Redeem Product
oldProd = [];
prodToBeInserted = [];
quantity = [];
total_amount = 0;
//dealerPoints = parseInt($(".dealerpoints").attr("rel"));
$(".Productredeem").live("click",function(){
    ID = $(this).attr("rel");
    title = $(this).attr("title");
    productPoints = parseInt($("#info_"+ID).attr("rel"));
    dealerPoints = parseInt($(".dealerpoints").attr("rel"));
    originalPoints = parseInt($(".dealerpoints").attr("originalPoints"));
    quant = parseInt($("#quant_"+ID).val());
    totalPoints = parseInt(productPoints) * quant;
    dealerPoints = parseInt(dealerPoints);
    if(isNaN(quant)==false){
        //alert(dealerPoints)
        //alert(dealerPoints+" < "+productPoints)
        if(quant==0){
            alert("Please input higher than 0")
        }else{
            if(totalPoints>dealerPoints){
                alert("Sorry you dont have enough points to redeem this product.");
            }else{
                //alert(true);
                if($("#quant_"+ID).val()==""){
                    quant = 0;
                    alert(false);
                }else{
                    //$(".productList").prepend("<li class='prod' id='prod_"+ID+"' amount='"+productPoints*quant+"'>"+title+"<span id='"+ID+"' style='float:right;color:red;cursor:pointer;font-size:14px;' class='deleteProduct' id='"+ID+"'>x</span></li><span id='details_"+ID+"'>Quantity: <span id='ctr_"+ID+"'>(1)</span><br/>Ammount: "+productPoints*quant+"</span>");
                    //$(".productList").prepend("<li class='prod' id='prod_"+ID+"' amount='"+productPoints*quant+"'>"+title+"<span id='"+ID+"' style='float:right;color:red;cursor:pointer;font-size:14px;' class='deleteProduct' id='"+ID+"'>x</span></li><span id='details_"+ID+"'>Quantity: <span id='ctr_"+ID+"'>(1)</span><br/>Ammount: "+productPoints*quant+"</span>");
                    $(".productList").prepend("<tr class='prod' id='prod_"+ID+"' amount='"+productPoints*quant+"'><td>"+title+"</td><td width='120'><center><span id='ctrProduct_"+ID+"'>1</span><span id='ctr_"+ID+"' class='display'>1</span></center></td><td width='50'><center><span id='"+ID+"' style='color:red;cursor:pointer;font-size:14px;' class='deleteProduct' id='"+ID+"'><center><img src='/images/icon/remove.png' width='15' title='delete this product'/></center></span></center></td></tr>");
                    prod_id = $(".prod").attr("id");
                    kapareho = "";
                    $("#prod_"+ID).show();
                    for(a=0;a<oldProd.length;a++){
                        if(oldProd[a]===prod_id){
                            kapareho++;
                        }
                    }
                    if(kapareho>0){
                        $("#prod_"+ID).remove();
                        counter = parseInt(kapareho)+1;
                        $("#ctr_"+ID).text("("+quant+")");
                        $("#ctrProduct_"+ID).text(quant);
                        total = productPoints * quant;
                        $("#prod_"+ID).attr("amount",total);
                        $(".totalSelectedPoints").html(total);
                    }else{
                        $("#ctr_"+ID).text("("+quant+")");
                        $("#ctrProduct_"+ID).text(quant);
                        //$(".productList").empty()
                        //$(".productList").prepend("<li class='prod' id='prod_"+ID+"'>"+title+"<span id='ctr_"+ID+"'>(1)</span><span style='float:right;color:red;cursor:pointer' class='deleteProduct'>x</span></li>");
                    }
                    total_amount = 0;
                    $(".prod").each(function(){
                        total_amount+=parseInt($(this).attr("amount"));
                    })
                    dealerPoints = originalPoints-total_amount
                    $(".dealerpoints").attr("rel",dealerPoints);
                    $(".dealerpoints").attr("value",dealerPoints);
                    $("#dealerSubPoints").text(dealerPoints+" "+"Points");
                    dealer_id = $("#info_"+ID).attr("dealer_id");
                    product_id = $(this).attr("rel");
                    product_type = $("#info_"+ID).attr("class");
                    $(".totalSelectedPoints").html(total_amount+" "+"Points"); // View total of selected product
                    oldProd.push(prod_id);
                    /*$.post("/ajax/redeem/",{product_type:product_type,dealerPoints:dealerPoints,redeem:"1",dealer_id:dealer_id,product_id:product_id},function(data){
                        $("#load_redeem").html(data);
                    })*/
                    //alert(oldProd)
                    $("#quant_"+ID).attr("disabled","disabled"); //disable the quantity field
                    $("#productredeem_"+ID).css("display","none"); //hiding the add button
                    $("#editRedeem_"+ID).css("display","inline-block"); //showing the edit button
                }
            }
        }
    }else{
        alert("Please input a number.");
    }
});
//delete redeem
ctr = 0;
$(".deleteProduct").live("click",function(){
    ID = this.id;
    remainingDealerPoints = parseInt($(".dealerpoints").val());
    productPoints = parseInt($("#prod_"+this.id).attr("amount"));
    remainingDealerPoints = remainingDealerPoints+productPoints;
    $(".dealerpoints").attr("rel",remainingDealerPoints);
        $(".dealerpoints").attr("value",remainingDealerPoints);
        $("#dealerSubPoints").text(remainingDealerPoints+" "+"Points");
        
    
    totalSelectedViewPoints = parseInt($(".totalSelectedPoints").text());
    viewTotalPointsSelected = totalSelectedViewPoints-productPoints;
    $(".totalSelectedPoints").html(viewTotalPointsSelected+" "+"Points"); // View total of selected product
    //$("#prod_"+this.id).fadeOut();
    //alert(oldProd.length)
    for(a=0;a<oldProd.length;a++){
        if(oldProd[a] == "prod_"+this.id+""){
            //console.log(oldProd[a]+" "+a)
            delete oldProd[a]
        }
    }
    $("#prod_"+this.id).fadeOut();
    $("#prod_"+this.id).remove();
    $("#details_"+this.id).fadeOut();
    $("#details_"+this.id).remove();
    $("#quant_"+ID).attr("disabled",false);
    $("#quant_"+ID).val("")
    //alert(oldProd+" "+ctr+" ");
    $("#editRedeem_"+ID).css("display","none");
    $("#productredeem_"+ID).css("display","inline-block");
})
$(".editProduct").live("click",function(){
    ID = $(this).attr("rel");
    remainingDealerPoints = parseInt($(".dealerpoints").val());
    productPoints = parseInt($("#prod_"+ID).attr("amount"));
    remainingDealerPoints = remainingDealerPoints+productPoints;
    $(".dealerpoints").attr("rel",remainingDealerPoints);
        $(".dealerpoints").attr("value",remainingDealerPoints);
        $("#dealerSubPoints").text(remainingDealerPoints+" "+"Points");
        
    totalSelectedViewPoints = parseInt($(".totalSelectedPoints").text());
    viewTotalPointsSelected = totalSelectedViewPoints-productPoints;
    $(".totalSelectedPoints").html(viewTotalPointsSelected+" "+"Points"); // View total of selected product
                                                            
    //$("#prod_"+this.id).fadeOut();
    //alert(oldProd.length)
    for(a=0;a<oldProd.length;a++){
        if(oldProd[a] == "prod_"+ID+""){
            //console.log(oldProd[a]+" "+a)
            delete oldProd[a]
        }
    }
    $("#prod_"+ID).fadeOut();
    $("#prod_"+ID).remove();
    $("#details_"+ID).fadeOut();
    $("#details_"+ID).remove();
    $("#quant_"+ID).attr("disabled",false);
    $("#quant_"+ID).val();
    //alert(oldProd+" "+ctr+" ");
    $("#editRedeem_"+ID).css("display","none");//for hiding the edit button
    $("#productredeem_"+ID).css("display","inline-block");//for showing the add button
})
//checkOut
$(".checkOut").live("click",function(){
    oldProd = [];
    redeem_id = "";
    total_amount = 0;
    dealer_id = $(this).attr("rel");
    prodToBeInserted = [];
    quantity = [];
    product_type = $(this).attr("prodType");
    $(".prod").each(function(){
        total_amount+=parseInt($(this).attr("amount"))
        prodToBeInserted.push(this.id.substr(5,this.id.length-1));
        quantity.push($("#ctr_"+this.id.substr(5,this.id.length-1)+"").text().substr(1,$("#ctr_"+this.id.substr(5,this.id.length-1)+"").text().length-2));
    })
    if(total_amount>0){
        conf = confirm("Are you sure do you want to proceed?");
        if(conf){
            //window.opener.location.reload();
            $.post("/ajax/redeem/",{trans_id:trans_id,redeem:"redeem",dealer_id:dealer_id,"prodToBeInserted[]":[prodToBeInserted],product_type:product_type,total_amount:total_amount,"quantity[]":[quantity]},function(data){
                //alert(data)
                if(data=="!"){
                    alert("Your Total Points is less than to your Total Redeem Points")
                }else{
                    window.open("/ajax/pdfGen?id="+trans_id+"","","width=750,height=500");
                }
            });
            $('html, body').animate({
                    scrollTop: $(".dealerPointsList").offset().top
                });
            ID = $(this).attr("rel"); // DealerCode
            action = "viewDealerPoints";
            $("#load").show();
            $(".dealerPointsList").html(null);
            //Get Dealer Information Points from the database
            $.post("/ajax/point/", {action:action,ID:ID}, function(dealerPointsList){
                $(".dealerPointsList").html(dealerPointsList);
                $("#load").hide();
            });
            $(".dealerRedeem").html(null);
            //alert(window.opener.location);
            
            //alert("Transaction finish");
            //window.close();//close window
            
        }
    }else{
        alert("Please choose an item to proceed.");
    }
})
//add transaction
$(".addTransaction").live("click",function(){
    oldProd = [];
    redeem_id = "";
    dealer_id = $(this).attr("rel");
    total_amount = 0;
    prodToBeInserted = [];
    quantity = [];
    product_type = $(this).attr("prodType");
    $(".prod").each(function(){
        total_amount+=parseInt($(this).attr("amount"))
        prodToBeInserted.push(this.id.substr(5,this.id.length-1));
        quantity.push($("#ctr_"+this.id.substr(5,this.id.length-1)+"").text().substr(1,$("#ctr_"+this.id.substr(5,this.id.length-1)+"").text().length-2));
    })
    if(total_amount>0){
        conf = confirm("Are you sure you want to proceed?");
        if(conf){
            //window.opener.location.reload();
            $.post("/ajax/redeem/",{trans_id:trans_id,redeem:"redeem",dealer_id:dealer_id,"prodToBeInserted[]":[prodToBeInserted],product_type:product_type,total_amount:total_amount,"quantity[]":[quantity]},function(data){
                //alert(data)
                if(data=="!"){
                    alert("Your Total Points is less than to your Total Redeem Points")
                }else{
                    $(".cOC").html('<input type="button" value="Print Receipt" class="button second_checkOut" style="float: left;" rel="'+dealer_id+'">');
                }
                
            });
            $('html, body').animate({
                    scrollTop: $(".dealerPointsList").offset().top
                });
            
            ID = $(this).attr("rel");
            action1 = "viewDealerPoints";
            $("#load").show();
            $(".dealerPointsList").html(null);
            //Get Dealer Information Points from the database
            $.post("/ajax/point/", {action:action1,ID:ID}, function(dealerPointsList){
                $(".dealerPointsList").html(dealerPointsList);
                $("#load").hide();
            });
            
            $(".dealerRedeem").html(null);
            //alert(window.opener.location);
            
            //alert("Transaction finish");
            //window.close();//close window
            
        }
    }else{
        alert("Please choose an item to proceed.");
    }
})
//second checkout or print receipt
$(".second_checkOut").live("click",function(){
    conf = confirm("Are you sure you want to proceed?");
        if(conf){
            alert("Click ok to view your recipe.");
            //window.open(""+trans_id+",'width=200,height=100'");
            window.open('/ajax/pdfGen?id='+trans_id+'','','width=750,height=500');
        }
})

// view points per dealer in table
$(".viewAllProductRedeemed").live("click",function(){
    
    $(".dealerRedeem").html(null);
    $('html, body').animate({
                    scrollTop: $(".dealerPointsList").offset().top
                });
    ID = $(this).attr("rel");
    action = "viewListOfPoints";
    $("#load").show();
    //Get Dealer Information Points from the database
    $.post("/ajax/pointList/", {action:action,ID:ID}, function(dealerPointsList){
        $(".dealerPointsList").html(dealerPointsList);
        $("#load").hide();
    });
    //for report
    $(".print").css("display","inline-block");
    $(".allTrans").css("display","none");
    $(".forReport").css("display","inline-block");
    $(".name").text("Dealer Name: "+$("#dealerName_"+ID).text()) //displaying the dealer name
})

$(".view_products").live("click",function(){
    forSelect = "0";
    Points = $(this).attr("id");
    Name = $(this).attr("rel");
    userID = $(this).attr("dealerCode");
    $("#loadProducts").show();
    $(".dealerRedeem").html(null);
    $("#viewPoints").css("opacity","0.4");
    //open new window to show the product
    $.post("/ajax/view_product/", {Points:Points,Name:Name,userID:userID,forSelect:forSelect}, function(result){
    setTimeout(function(){
            $(".dealerRedeem").html(result);
            $("#loadProducts").hide();
            $('html, body').animate({
                    scrollTop: $(".dealerRedeem").offset().top
                });
            $("#viewPoints").css("opacity","1");
    }, 1000);
        
    });
});



//----------------------------------------------------------------------------------------//
//excess div of date picker
$(".ui-datepicker-div").hide();


// Upload Scheduler
ulastLog = $("#userLastLogin").val();
uUpdateTimeLog = $("#userUpdateRecordTime").val();
realTime = $("#userRealTime").val();
ulastLogacc = $("#userLastLogin").attr("admin");

if(ulastLogacc=="Admin"||ulastLogacc=="Manager"){
    // Logout
    if(uUpdateTimeLog>realTime){
        action = "logout";
        $.post("/ajax/actions/",{action:action,ulastLog:ulastLog,uUpdateTimeLog:uUpdateTimeLog,realTime:realTime}, function(res){
            
        });
    }
    if(ulastLog==""||uUpdateTimeLog==""){
        
    }else{
        if(ulastLog=="1"){
            //alert("update");
            action = $(".AutoUpdate_invoice").attr("action");
            locFile = $(".AutoUpdate_invoice").attr("rel");
            
            
            action1 = $(".AutoUpdate_product").attr("action");
            locFile1 = $(".AutoUpdate_product").attr("rel");
            $("#loadingUpdateTimer").show();
            //$("#load").show();
            $.post("/ajax/update/",{action:action,locFile:locFile}, function(res){
                if(res == 'Folder location is empty.'){
                    //$("#load").hide();
                    //$("#warning").show().fadeOut(3000);
                    $("#loadingUpdateTimer").hide();
                }
                else{
                    if(res == 'Invalid File Format.'){
                        //$("#load").hide();
                        //$("#wrong").show().fadeOut(3000);
                        //window.location.reload();
                        //$("#loadingUpdateTimer").animate().slideDown("slow");
                        $("#loadingUpdateTimer").hide();
                    }
                    else
                    {
                        if(res == 'File is already uploaded.'){
                            $("#loadingUpdateTimer").hide();
                            $("#loadProduct").hide();
                            /*
                            $("#warn").show().fadeOut(3000);
                            
                            $("#warning").hide();
                            $("#correct").hide();
                            */
                        }else{
                            if(res == 'Files was successfully uploaded.'){
                                //$("#load").hide();
                                //$("#correct").show().fadeOut(3000);
                                //window.location.reload();
                                //$("#loadingUpdateTimer").animate().slideDown("slow");
                                $("#loadingUpdateTimer").hide().fadeOut('slow');
                            }
                        }
                    }
                }
            });
            
            $.post("/ajax/uploadValidation/",{action:action1,locFile:locFile1}, function(res){    
                if(res=="There was an Error while uploading your file."){
                    showNotification({
                        message: "There was an Error while uploading your file.",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    $("#loadProduct").hide();
                    $("#loadingUpdateTimer").hide();
                }else{
                    if(res=="Folder location is empty."){
                        showNotification({
                            message: "Folder location is empty.",
                            type: "error",
                            autoClose: true,
                            duration: 5
                        });
                        $("#loadProduct").hide();
                        $("#loadingUpdateTimer").hide();
                    }else{
                        if(res=="Invalid File Format."){
                            showNotification({
                                message: "Invalid File Format.",
                                type: "error",
                                autoClose: true,
                                duration: 5
                            });
                            $("#loadProduct").hide();
                            $("#loadingUpdateTimer").hide();
                        }else{
                            if(res=="File is already uploaded."){
                                showNotification({
                                    message: "File is already uploaded.",
                                    type: "error",
                                    autoClose: true,
                                    duration: 5
                                });
                                $("#loadProduct").hide();
                                $("#loadingUpdateTimer").hide();
                            }else{
                                if(res=="PLINE type doesnt match on our record."){
                                    showNotification({
                                        message: "PLINE type doesnt match on our record.",
                                        type: "error",
                                        autoClose: true,
                                        duration: 5
                                    });
                                    $("#loadProduct").hide();
                                    $("#loadingUpdateTimer").hide();
                                }else{
                                    $.post("/ajax/update/",{action:action1,locFile:locFile1}, function(update){
                                        showNotification({
                                            message: "File was successfully uploaded.",
                                            type: "success",
                                            autoClose: true,
                                            duration: 5
                                        });
                                        $("#loadProduct").hide();
                                        $("#loadingUpdateTimer").hide();
                                    });
                                }
                                
                            }
                        }
                    }
                }
            });
        }else{
            if(uUpdateTimeLog==realTime){
                //alert("same time");
                action = $(".AutoUpdate_invoice").attr("action");
                locFile = $(".AutoUpdate_invoice").attr("rel");
                
                
                action1 = $(".AutoUpdate_product").attr("action");
                locFile1 = $(".AutoUpdate_product").attr("rel");
                $("#loadingUpdateTimer").show();
                //$("#load").show();
                $.post("/ajax/update/",{action:action,locFile:locFile}, function(res){
                    if(res == 'Folder location is empty.'){
                        //$("#load").hide();
                        //$("#warning").show().fadeOut(3000);
                        $("#loadingUpdateTimer").hide();
                    }
                    else{
                        if(res == 'Invalid File Format.'){
                            //$("#load").hide();
                            //$("#wrong").show().fadeOut(3000);
                            //window.location.reload();
                            //$("#loadingUpdateTimer").animate().slideDown("slow");
                            $("#loadingUpdateTimer").hide();
                        }
                        else
                        {
                            if(res == 'File is already uploaded.'){
                                $("#loadingUpdateTimer").hide();
                                $("#loadProduct").hide();
                                /*
                                $("#warn").show().fadeOut(3000);
                                
                                $("#warning").hide();
                                $("#correct").hide();
                                */
                            }else{
                                if(res == 'Files was successfully uploaded.'){
                                    //$("#load").hide();
                                    //$("#correct").show().fadeOut(3000);
                                    //window.location.reload();
                                    //$("#loadingUpdateTimer").animate().slideDown("slow");
                                    $("#loadingUpdateTimer").hide().fadeOut('slow');
                                }
                            }
                        }
                    }
                });
                
                
            $.post("/ajax/uploadValidation/",{action:action1,locFile:locFile1}, function(res){        
                if(res=="There was an Error while uploading your file."){
                    showNotification({
                        message: "There was an Error while uploading your file.",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    $("#loadingUpdateTimer").hide().fadeOut('slow');
                }else{
                    if(res=="Folder location is empty."){
                        showNotification({
                            message: "Folder location is empty.",
                            type: "error",
                            autoClose: true,
                            duration: 5
                        });
                        $("#loadingUpdateTimer").hide().fadeOut('slow');
                    }else{
                        if(res=="Invalid File Format."){
                            showNotification({
                                message: "Invalid File Format.",
                                type: "error",
                                autoClose: true,
                                duration: 5
                            });
                            $("#loadingUpdateTimer").hide().fadeOut('slow');
                        }else{
                            if(res=="File is already uploaded."){
                                showNotification({
                                    message: "File is already uploaded.",
                                    type: "error",
                                    autoClose: true,
                                    duration: 5
                                });$("#loadingUpdateTimer").hide().fadeOut('slow');
                            }else{
                                if(res=="PLINE type doesnt match on our record."){
                                    showNotification({
                                        message: "PLINE type doesnt match on our record.",
                                        type: "error",
                                        autoClose: true,
                                        duration: 5
                                    });$("#loadingUpdateTimer").hide().fadeOut('slow');
                                }else{
                                    $.post("/ajax/update/",{action:action1,locFile:locFile1}, function(update){
                                        showNotification({
                                            message: "File was successfully uploaded.",
                                            type: "success",
                                            autoClose: true,
                                            duration: 5
                                        });$("#loadingUpdateTimer").hide().fadeOut('slow');
                                    });
                                }
                                
                            }
                        }
                    }
                }
            });
            }else{
                if(uUpdateTimeLog<realTime){
                    //alert("Lumagpas");
                    
                    time = realTime.substr(6,realTime.length);
                    
                    action = $(".AutoUpdate_invoice").attr("action");
                    locFile = $(".AutoUpdate_invoice").attr("rel");
                    
                    action1 = $(".AutoUpdate_product").attr("action");
                    locFile1 = $(".AutoUpdate_product").attr("rel");
                    
                    if(time=="AM"||time=="PM"){
                        $("#loadingUpdateTimer").hide();
                    }else{
                        $("#loadingUpdateTimer").show();
        
                        //$("#load").show();
                        $.post("/ajax/update/",{action:action,locFile:locFile}, function(res){
                            if(res == 'Folder location is empty.'){
                                $("#load").hide();
                                $("#warning").show().fadeOut(3000);
                                $("#loadingUpdateTimer").hide();
                            }
                            else{
                                if(res == 'Invalid File Format.'){
                                    $("#load").hide();
                                    $("#wrong").show().fadeOut(3000);
                                    //window.location.reload();
                                    //$("#loadingUpdateTimer").animate().slideDown("slow");
                                    $("#loadingUpdateTimer").hide();
                                }
                                else
                                {
                                    
                                    if(res == 'File is already uploaded.'){
                                        $("#loadingUpdateTimer").hide();
                                        /*
                                        $("#warn").show().fadeOut(3000);
                                        
                                        $("#warning").hide();
                                        $("#correct").hide();
                                        */
                                    }else{
                                        if(res == 'Files was successfully uploaded.'){
                                            $("#load").hide();
                                            $("#correct").show().fadeOut(3000);
                                            //window.location.reload();
                                            //$("#loadingUpdateTimer").animate().slideDown("slow");
                                            $("#loadingUpdateTimer").hide().fadeOut('slow');
                                        }
                                    }
                                }
                            }
                        });
                    $.post("/ajax/uploadValidation/",{action:action1,locFile:locFile1}, function(res){        
                        if(res=="There was an Error while uploading your file."){
                            showNotification({
                                message: "There was an Error while uploading your file.",
                                type: "error",
                                autoClose: true,
                                duration: 5
                            });
                            $("#loadingUpdateTimer").hide().fadeOut('slow');
                        }else{
                            if(res=="Folder location is empty."){
                                showNotification({
                                    message: "Folder location is empty.",
                                    type: "error",
                                    autoClose: true,
                                    duration: 5
                                });
                                $("#loadingUpdateTimer").hide().fadeOut('slow');
                            }else{
                                if(res=="Invalid File Format."){
                                    showNotification({
                                        message: "Invalid File Format.",
                                        type: "error",
                                        autoClose: true,
                                        duration: 5
                                    });
                                    $("#loadingUpdateTimer").hide().fadeOut('slow');
                                }else{
                                    if(res=="File is already uploaded."){
                                        showNotification({
                                            message: "File is already uploaded.",
                                            type: "error",
                                            autoClose: true,
                                            duration: 5
                                        });
                                        $("#loadingUpdateTimer").hide().fadeOut('slow');
                                    }else{
                                        if(res=="PLINE type doesnt match on our record."){
                                            showNotification({
                                                message: "PLINE type doesnt match on our record.",
                                                type: "error",
                                                autoClose: true,
                                                duration: 5
                                            });
                                            $("#loadingUpdateTimer").hide().fadeOut('slow');
                                        }else{
                                            $.post("/ajax/update/",{action:action1,locFile:locFile1}, function(update){
                                                showNotification({
                                                    message: "File was successfully uploaded.",
                                                    type: "success",
                                                    autoClose: true,
                                                    duration: 5
                                                });
                                                $("#loadingUpdateTimer").hide().fadeOut('slow');
                                            });
                                        }
                                        
                                    }
                                }
                            }
                        }
                    });
                    }
                }
            }
        }
    }
}
// generate one text file
$.post("/ajax/actions",{action:"generateTxtFiles"}, function(e){
    
});
});
/* Set Active Nav */
function setActivNav(idOfNav){
    $(".navLink").each(function(){
        if(this.id==idOfNav){
            $("#"+idOfNav).addClass("menuActive");
        }else{
            $("#"+this.id).removeClass("menuActive");
        }
    })
}
//allownum only
function allownum(evt){
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
//Date Picker
function MakeStartEndPicker(startElement, endElement)
{
        $(startElement).datepicker({
                dateFormat: 'yy/mm/dd', 
                beforeShow: function(input)
                {
                var date2 =  $(endElement).datepicker('getDate');
                if(date2 != undefined) return { maxDate: date2 };
                }
        });

        $(endElement).datepicker({
                dateFormat: 'yy/mm/dd', 
                beforeShow: function(input)
                {
                var date1 =  $(startElement).datepicker('getDate');
                if(date1 != undefined) return { minDate: date1 };
                }
        });
}